package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class TestServiceImpl implements TestService {

    private  final Lock lock = new ReentrantLock();
    @Autowired
    private RedisTemplate redisTemplate;

    //分布式锁
    @Override
    public void lock(){
        //分布式锁   Redis中存在了 Lock  表示已经上锁了     不存在表示未上锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "1212");




        if (lock){
            //lock： true  表示已经上锁了
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            num++;
            redisTemplate.opsForValue().set("num",num);

            //删除 Lock 表示解锁
            redisTemplate.delete("lock");
        }else {
            //lock ： false  表示  已经上锁了
             lock();
        }

    }




//本地锁代码测试
  /*   @Override
    public void lock() {
       //本地锁
        lock.lock();
        try {
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            num++;
            redisTemplate.opsForValue().set("num",num);
        } finally {
            lock.unlock();
        }


    }*/
}
